#include "bsp_dma.h"
#include "bsp_usart.h"

BOOL _fTransferFinished = FALSE;

void DMA_MemCopy(void* pDest, const void* pSrc, uint16_t length)
{
	dma_multi_data_parameter_struct dma_init_struct;
	
	rcu_periph_clock_enable(RCU_DMA1);
	// DMA1, channel1, subperiph0
	dma_deinit(DMA1, DMA_CH1);
	
	dma_init_struct.circular_mode		= DMA_CIRCULAR_MODE_DISABLE;
	dma_init_struct.critical_value		= DMA_FIFO_4_WORD;
	dma_init_struct.direction			= DMA_MEMORY_TO_MEMORY;
	dma_init_struct.memory0_addr		= (uint32_t)pDest;
	dma_init_struct.memory_burst_width	= DMA_MEMORY_BURST_4_BEAT;
	dma_init_struct.memory_inc			= DMA_MEMORY_INCREASE_ENABLE;
	dma_init_struct.memory_width		= DMA_MEMORY_WIDTH_32BIT;
	dma_init_struct.number				= length;
	dma_init_struct.periph_addr			= (uint32_t)pSrc;
	dma_init_struct.periph_burst_width	= DMA_PERIPH_BURST_4_BEAT;
	dma_init_struct.periph_inc			= DMA_PERIPH_INCREASE_ENABLE;
	dma_init_struct.periph_width		= DMA_PERIPH_WIDTH_32BIT;
	dma_init_struct.priority			= DMA_PRIORITY_HIGH;
	
	dma_multi_data_mode_init(DMA1, DMA_CH1, &dma_init_struct);
	dma_channel_subperipheral_select(DMA1, DMA_CH1, DMA_SUBPERI0);
	
	dma_interrupt_enable(DMA1, DMA_CH1, DMA_CHXCTL_FTFIE);
	nvic_irq_enable(DMA1_Channel1_IRQn, 3, 0);
	
	dma_channel_enable(DMA1, DMA_CH1);
}

void DMA1_Channel1_IRQHandler()
{
	if (dma_interrupt_flag_get(DMA1, DMA_CH1, DMA_INT_FLAG_FTF) == SET)
	{
		dma_interrupt_flag_clear(DMA1, DMA_CH1, DMA_INT_FLAG_FTF);
		_fTransferFinished = TRUE;
//		LED0_TOGGLE();
	}	
}
